import json
import sys, os

'''
使用方法：
1. 导出swagger接口文档
2. 将swagger文档导入apipost，不做编辑
3. 导出apipost接口文档
4. 使用本脚本进行解析
'''



'''
步骤：
1.读取文件
2. 将apis根据目录划分
3. 将每个目录中的接口写在一个文件中
'''


# 单个接口解析
def api_parse(data: dict):
    print("接口： ", data)
    name = data["name"]
    method = data["method"]
    request: dict = data["request"]
    url = request["url"]
    # 请求头
    header_para: list = request["header"]["parameter"]
    header_para_dict = {}
    for para in header_para:
        key = para["key"]
        value = para["value"]
        # not_null = para["not_null"]
        # description = para["description"]
        header_para_dict[key] = value

    # 请求体
    body_para_dict = {}
    if method == "POST" and "body" in request.keys() and "raw_para" in request["body"].keys():
        body_para = request["body"]["raw_para"]
        for para in body_para:
            key = para["key"]
            value = para["value"]
            # not_null = para["not_null"]
            # description = para["description"]
            body_para_dict[key] = value

    api = {
        "name": name,
        "method": method,
        "url": url,
        "header": header_para_dict,
        "body": body_para_dict
    }
    return api


# 文件夹解析
def folder_parse(folder: dict):
    name = folder["name"]
    file_name = f"../apis/{name}.py"
    folder_apis: list = folder["children"]
    with open(file_name, "w+", encoding="utf-8") as file:
        file.write("import requests\n")
        file.write("from config import RunConfig")
        for api in folder_apis:
            api_data = api_parse(api)  # 解析单个api

            file.write("\n\n")
            file.write("def " + api_data["name"] + "(para):\n")
            if api_data["method"] == "POST":
                file.write("    response = requests.post(\n")
                file.write("        url=RunConfig.url + " + '"/'+ api_data["url"] + '"' +",\n")
                file.write("        headers=RunConfig.headers" + ",\n")
                file.write("        json=para" + ",\n")
                file.write("        verify=False\n")
                file.write("    )\n")

            if api_data["method"] == "GET":
                file.write("    response = requests.get(\n")
                file.write("        url=RunConfig.url + " + '"/' + api_data["url"] + '"' + ",\n")
                file.write("        headers=RunConfig.headers" + ",\n")
                file.write("        verify=False\n")
                file.write("    )\n")
            file.write("    return response\n")


# 解析所有的api
def apis_parse(apis: list):
    for folder in apis:
        folder_parse(folder)


def apis_json_parse(file_path: str):
    with open(file_path, "r", encoding="utf-8") as f:
        data = json.load(f)
        apis_info = data["apis"]
        apis_parse(apis_info)


if __name__ == "__main__":
    file_path = "../data/AI-wt_v1.json"
    apis_json_parse(file_path)



